import axios from 'axios'
import store from '@/store'
import {Message} from 'element-ui'
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000,
})

//请求拦截器
service.interceptors.request.use(
  (config)=>{
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config}, 
  (error) => {
  // 失败执行promise
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    //判断返回的数据类型是否为blob类型是则直接返回数据
    if (response.data instanceof Blob) return response.data 
    const { data, message, success } = response.data // 默认json格式
    if (success) {
      return data
    } else {
      Message({ type: 'error', message })
      return Promise.reject(new Error(message))
    }
  }, 
  async(error) => {
    if(error.response.status === 401){
      Message({type:'warning',message:'token超时'})
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(error)
    }
    // error.message
    Message({ type: 'error', message: error.message })
    return Promise.reject(error)
  })
export default service